package com.clss.commandhelper.function.casedetail;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.clss.commandhelper.R;
import com.clss.commandhelper.base.BaseActivity;
import com.clss.commandhelper.function.caseAddInformation.CaseAddInformationActivity;
import com.clss.commandhelper.function.home.UploadLocationService;
import com.clss.commandhelper.function.newEvidence.EvidenceAndNewCaseActivity;
import com.clss.commandhelper.function.newEvidence.InfoTaskDispatch;
import com.clss.commandhelper.function.supportTeam.SupportTeamListActivity;
import com.clss.commandhelper.function.videoroom.WebRtcActivity;
import com.clss.commandhelper.net.ApiConstants;
import com.clss.commandhelper.tools.Constant;
import com.clss.commandhelper.tools.DownloadHelper;
import com.clss.commandhelper.tools.MediaManager;
import com.clss.commandhelper.tools.SdCard;
import com.clss.commandhelper.tools.Utils;
import com.clss.commandhelper.tools.eventbus.EventBusHelper;
import com.clss.commandhelper.tools.eventbus.EventBusMessage;
import com.clss.commandhelper.tools.janus.entity.MediaSessionBean;
import com.clss.commandhelper.view.CountDownTextView;
import com.clss.commandhelper.view.ShowAllListView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author liuv
 */
public class CaseDetailActivity extends BaseActivity implements CaseDetailPresenter.CaseDetailView,
        SwipeRefreshLayout.OnRefreshListener {
    private static final String TAG = "CaseDetailActivity";

    public static final String TASK_ID = "TASK_ID";
    public static final String ID = "ID";
    public static final String DISPATCH_STATUS = "DISPATCH_STATUS";
    public static final String AREA_CODE = "AREA_CODE";

    private static final int DISPATCH_STATUS_TYPE_1 = 1;
    private static final int DISPATCH_STATUS_TYPE_2 = 2;
    private static final int DISPATCH_STATUS_TYPE_3 = 3;

    @BindView(R.id.include_top_bar_left_iv)
    ImageView includeTopBarLeftIv;
    @BindView(R.id.include_top_bar_title_tv)
    TextView includeTopBarTitleTv;
    @BindView(R.id.case_detial_type_tv)
    TextView caseDetialTypeTv;
    @BindView(R.id.case_detial_level_tv)
    TextView caseDetialLevelTv;
    @BindView(R.id.case_detial_address_tv)
    TextView caseDetialAddressTv;
    @BindView(R.id.case_detial_info_tv)
    TextView caseDetialInfoTv;
    @BindView(R.id.informer_detail_info_update_ll)
    LinearLayout informerDetailInfoUpdateLl;
    @BindView(R.id.case_detail_get_down_btn)
    Button caseDetailGetDownBtn;
    @BindView(R.id.case_detail_start_video_btn)
    Button caseDetailStartVideoBtn;
    @BindView(R.id.case_detail_lv)
    ShowAllListView caseDetailLv;
    @BindView(R.id.case_detail_data_content_ll)
    LinearLayout caseDetailDataContentLl;
    @BindView(R.id.case_detail_srl)
    SwipeRefreshLayout caseDetailSrl;
    @BindView(R.id.include_top_bar_right_iv)
    ImageView includeTopBarRightIv;
    @BindView(R.id.case_detail_take_evidence_btn)
    Button caseDetailTakeEvidenceBtn;
    @BindView(R.id.case_detail_name_tv)
    TextView caseDetailNameTv;
    @BindView(R.id.include_top_bar_right_tv)
    TextView includeTopBarRightTv;
    @BindView(R.id.case_detail_down_btn_layout)
    LinearLayout mCaseDetailDownBtnLayout;
    @BindView(R.id.case_detail_take_support_btn)
    Button mCaseDetailTakeSupportBtn;

    private String mTaskId;
    private CaseDetailPresenter mCaseDetailPresenter;
    private CaseDetailBean mCaseDetailBean;
    private InfoTaskDispatch infoTaskDispatch;
    private String mDispatchId;
    private int mStatus;
    private String mAreaCode;
    public List<DataContentBean> dataContentBeans;
    private DataContentAdapter adapter;
    private Dialog dialog;
    private CountDownTextView countDownTextView;
    private String[] types;
    private String[] levels;

    @Override
    protected int setViewId() {
        return R.layout.activity_case_detail;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        mTaskId = bundle.getString(TASK_ID, "");
        mDispatchId = bundle.getString(ID, "");
        mStatus = bundle.getInt(DISPATCH_STATUS, -1);
        mAreaCode = bundle.getString(AREA_CODE, "");
        if (mStatus != -1){
            setBottomBtnStatus();
        }
        includeTopBarTitleTv.setText("事件详情");
        caseDetailSrl.setOnRefreshListener(this);
        mCaseDetailPresenter = new CaseDetailPresenter();
        mCaseDetailPresenter.setCaseDetailView(this);
        types = getResources().getStringArray(R.array.task_type);
        levels = getResources().getStringArray(R.array.task_police_level);
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        mCaseDetailPresenter.getCaseDetail();
        dataContentBeans = new ArrayList<>();

        adapter = new DataContentAdapter(this, 0);
        caseDetailLv.setAdapter(adapter);
        Utils.setListViewHeightBasedOnChildren(caseDetailLv);
        initLocation(null);
    }

    private void setBottomBtnStatus() {
        switch (mStatus) {
            case DISPATCH_STATUS_TYPE_1:
                caseDetailGetDownBtn.setVisibility(View.VISIBLE);
                caseDetailStartVideoBtn.setVisibility(View.GONE);
                includeTopBarRightTv.setVisibility(View.GONE);
                mCaseDetailTakeSupportBtn.setVisibility(View.GONE);
                break;
            case DISPATCH_STATUS_TYPE_2:
                caseDetailGetDownBtn.setVisibility(View.GONE);
                caseDetailStartVideoBtn.setVisibility(View.VISIBLE);
                caseDetailTakeEvidenceBtn.setVisibility(View.VISIBLE);
                includeTopBarRightTv.setText("补充信息");
                includeTopBarRightTv.setVisibility(View.VISIBLE);
                mCaseDetailTakeSupportBtn.setVisibility(View.VISIBLE);
                break;
            case DISPATCH_STATUS_TYPE_3:
//                caseDetailGetDownBtn.setVisibility(View.GONE);
//                caseDetailStartVideoBtn.setVisibility(View.GONE);
//                caseDetailTakeEvidenceBtn.setVisibility(View.GONE);
                mCaseDetailDownBtnLayout.setVisibility(View.GONE);
                includeTopBarRightTv.setVisibility(View.GONE);
                break;
            default:
        }
    }

    @Override
    public void onEventMainThread(EventBusMessage eventBusMessage) {
        super.onEventMainThread(eventBusMessage);
        if (eventBusMessage.getCode() == EventBusHelper.LOCATION_SUCCESS){
            UploadLocationService.startUploadLocation(this);
        }
    }

    @Override
    public void responseError(int code, String msg) {
        dismissLoadingDialog();
        if (caseDetailSrl.isRefreshing()) {
            caseDetailSrl.setRefreshing(false);
        }
        if (null != msg) {
            showShortToast(msg);
        }
    }

    @Override
    public void requestFailure(Throwable t) {
        super.requestFailure(t);
        if (caseDetailSrl.isRefreshing()) {
            caseDetailSrl.setRefreshing(false);
        }
    }

    @OnClick({R.id.include_top_bar_left_iv, R.id.include_top_bar_title_tv,
            R.id.case_detail_get_down_btn, R.id.case_detail_start_video_btn,R.id.case_detail_take_evidence_btn,
            R.id.include_top_bar_right_tv,R.id.case_detail_take_support_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.include_top_bar_left_iv:
                finish();
                break;
            case R.id.include_top_bar_title_tv:

                break;
            case R.id.case_detail_get_down_btn:
                mCaseDetailPresenter.changeCaseStatus(DISPATCH_STATUS_TYPE_2);
                break;
            case R.id.case_detail_start_video_btn:
                mCaseDetailPresenter.joinVideoRoom();
                break;
            case R.id.case_detail_take_evidence_btn:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 2);
                bundle.putSerializable("info", infoTaskDispatch);
                Utils.startActivity(this, EvidenceAndNewCaseActivity.class, bundle);
                break;
            case R.id.include_top_bar_right_tv:
                Bundle bundle1 = new Bundle();
                bundle1.putString("id", mTaskId);
                Utils.startActivity(this, CaseAddInformationActivity.class, bundle1);
//                mCaseDetailPresenter.changeCaseStatus(DISPATCH_STATUS_TYPE_3);
                break;
            case R.id.case_detail_take_support_btn:
                Bundle bundle2 = new Bundle();
                bundle2.putString("id",mTaskId);
                Utils.startActivity(this, SupportTeamListActivity.class,bundle2);
                break;
            default:
        }
    }

    @Override
    public void getCaseDetailSuccess(CaseDetailBean bean) {
        if (caseDetailSrl.isRefreshing()) {
            caseDetailSrl.setRefreshing(false);
        }
        mCaseDetailBean = bean;
//        if (mStatus == -1) {
//            mStatus = bean();
//            setBottomBtnStatus();
//        }
        if (mAreaCode == null || mAreaCode.equals("")) {
            mAreaCode = bean.getAreaCode();
        }
        caseDetialTypeTv.setText(types[mCaseDetailBean.getPoliceInfoType()]);
        caseDetialLevelTv.setText(levels[mCaseDetailBean.getPoliceInfoLevel()]);
        if (mCaseDetailBean.getPoliceInfoComment() != null) {
            caseDetialInfoTv.setText(mCaseDetailBean.getPoliceInfoComment());
        }
        if (mCaseDetailBean.getTaskName() != null) {
            caseDetailNameTv.setText(mCaseDetailBean.getTaskName());
        }
    }

    @Override
    public String getCaseDetailTaskId() {
        return mTaskId;
    }

    @Override
    public String getCaseDetailDispatchId() {
        return mDispatchId;
    }

    @Override
    public String getAreaCode() {
        return mAreaCode;
    }

    @Override
    public void joinVideoRoomSuccess(MediaSessionBean bean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constant.VIDEO_CASE_INFO, bean);
        bundle.putString(WebRtcActivity.DISPLAY_ID, mCaseDetailBean.getReceiveUserId());
        Utils.startActivity(this, WebRtcActivity.class, bundle);
    }

    @Override
    public void changeCaseStatusSuccess(int status) {
        mStatus = status;
        setBottomBtnStatus();
    }

    @Override
    public void getDetailListSuccess(List<DataContentBean> list) {
        dismissLoadingDialog();
        dataContentBeans.clear();
        if (list.size() > 0) {
            caseDetailDataContentLl.setVisibility(View.VISIBLE);
            dataContentBeans.addAll(list);
        } else {
            caseDetailDataContentLl.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
        Utils.setListViewHeightBasedOnChildren(caseDetailLv);
    }

    @Override
    public void updateTaskLocationSuccess() {
        mCaseDetailPresenter.getCaseDetail();
        showLongToast("提交当前位置成功");
    }

    @Override
    public void getLocationFail() {
        showLongToast("定位失败，正在重新定位，请稍后再试");
        initLocation(null);
    }

    @Override
    public void getDispatchSuccess(InfoTaskDispatch infoTaskDispatch) {
        this.infoTaskDispatch = infoTaskDispatch;
        this.infoTaskDispatch.setAreaCode(mCaseDetailBean.getAreaCode());
        if (mStatus == -1){
            mStatus = infoTaskDispatch.getDispatchStatus();
            setBottomBtnStatus();
        }
    }

    @Override
    public void onRefresh() {
        mCaseDetailPresenter.getCaseDetail();
    }

    private void startPlaying(String localPath) {
        MediaManager.playSound(localPath,
                mp -> {
                    if (dialog.isShowing()) {
                        countDownTextView.setTime(0);
                    }
                    dialog.dismiss();
                });
    }

    private void stopPlaying() {
        MediaManager.playstop();
    }

    public void initDialogAndStartPlay(String localPath, int duration) {
        if (dialog != null) {
            dialog.show();
            if (dialog.isShowing()) {
                countDownTextView.setTime(duration);
                countDownTextView.beginRun();
                startPlaying(localPath);
            }
            return;
        }

        dialog = new Dialog(getActContext(), R.style.recordbutton_alert_dialog);
        View contentView = LayoutInflater.from(getActContext()).inflate(R.layout.dialog_play_audio, null);
        ImageView mImageView = (ImageView) contentView.findViewById(R.id.dialog_play_audio_iv);
        mImageView.setImageDrawable(ContextCompat.getDrawable(getActContext(), R.drawable.play_audio_anim));
        AnimationDrawable animationDrawable = (AnimationDrawable) mImageView.getDrawable();
        animationDrawable.start();
        countDownTextView = (CountDownTextView) contentView.findViewById(R.id.dialog_play_audio_cdtv);
        countDownTextView.setTime(duration);
        countDownTextView.beginRun();
        TextView mTitleTv = (TextView) contentView.findViewById(R.id.dialog_play_audio_tv);
        Button stop = (Button) contentView.findViewById(R.id.dialog_play_btn_record_stop);
        stop.setOnClickListener(v -> {
            countDownTextView.stopRun();
            stopPlaying();
            dialog.dismiss();
        });
        dialog.setContentView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        dialog.setOnDismissListener(dialog -> {
            countDownTextView.stopRun();
            stopPlaying();
        });
        dialog.setCancelable(false);
        dialog.onWindowFocusChanged(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        if (dialog.isShowing()) {
            startPlaying(localPath);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public class DataContentAdapter extends ArrayAdapter {


        public DataContentAdapter(@NonNull Context context, int resource) {
            super(context, resource);
        }

        @Override
        public int getCount() {
            return dataContentBeans.size();
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View view = getLayoutInflater().inflate(R.layout.item_task_detail, null);
            TextView address = (TextView) view.findViewById(R.id.item_task_address);
            TextView time = (TextView) view.findViewById(R.id.item_task_time);
            TextView content = (TextView) view.findViewById(R.id.item_task_content);
            ImageView imageView = view.findViewById(R.id.item_task_av);
            address.setText(dataContentBeans.get(position).getAddress());
            time.setText(dataContentBeans.get(position).getTime());
            content.setText(dataContentBeans.get(position).getContent());
            if (dataContentBeans.get(position).getType() == 1) {
                content.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
            } else if (dataContentBeans.get(position).getType() == 14) {
                imageView.setVisibility(View.VISIBLE);
                content.setVisibility(View.GONE);
                Utils.showUrlImage(getActContext(), ApiConstants.getUploadFileUrl(dataContentBeans.get(position).getFileId()), imageView);

                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("pic", ApiConstants.getUploadFileUrl(dataContentBeans.get(position).getFileId()));
                        Utils.startActivity(CaseDetailActivity.this, ShowImageActivity.class, bundle);
                    }
                });

            } else if (dataContentBeans.get(position).getType() == 15) {
                imageView.setVisibility(View.VISIBLE);
                content.setVisibility(View.GONE);
                imageView.setImageResource(R.mipmap.icon_play);
                imageView.setBackgroundColor(ContextCompat.getColor(getActContext(), R.color.color_1b1b1b));
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String path = SdCard.getVideo() + "/" + dataContentBeans.get(position).getFileId() + ".mp4";
                        if (DownloadHelper.isExistDir(SdCard.getVideo(),
                                dataContentBeans.get(position).getFileId() + ".mp4")) {
                            Uri contentUri = FileProvider.getUriForFile(getActContext(),
                                    getApplicationContext().getPackageName() + ".FileProvider",
                                    new File(path));
                            Intent it = new Intent(Intent.ACTION_VIEW);
                            it.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            it.setDataAndType(contentUri, "video/mp4");
                            startActivity(it);
                        } else {
                            showLoadingDialog("下载中，请稍后...");
                            DownloadHelper
                                    .download(ApiConstants.getUploadFileUrl(dataContentBeans.get(position).getFileId()), SdCard.getVideo(),
                                            dataContentBeans.get(position).getFileId() + ".mp4", new DownloadHelper.OnDownloadListener() {
                                                @Override
                                                public void onDownloadSuccess(final String path) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            dismissLoadingDialog();
                                                            Uri contentUri = FileProvider.getUriForFile(getActContext(),
                                                                    getApplicationContext().getPackageName() + ".FileProvider",
                                                                    new File(path));
                                                            Intent it = new Intent(Intent.ACTION_VIEW);
                                                            it.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                                            it.setDataAndType(contentUri, "video/mp4");
                                                            startActivity(it);
                                                        }
                                                    });

                                                }

                                                @Override
                                                public void onDownloading(int progress) {
                                                }

                                                @Override
                                                public void onDownloadFailed() {
                                                    dismissLoadingDialog();
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            showShortToast("下载失败");
                                                        }
                                                    });
                                                }
                                            });
                        }
                    }
                });
            } else if (dataContentBeans.get(position).getType() == 28) {
                imageView.setVisibility(View.VISIBLE);
                content.setVisibility(View.GONE);
                imageView.setBackgroundColor(ContextCompat.getColor(getActContext(), R.color.color_efeff4));
                imageView.setImageResource(R.mipmap.icon_voice);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String path = SdCard.getAudio() + "/" + dataContentBeans.get(position).getFileId() + ".mp3";
                        if (DownloadHelper.isExistDir(SdCard.getAudio(),
                                dataContentBeans.get(position).getFileId() + ".mp3")) {
                            initDialogAndStartPlay(path, dataContentBeans.get(position).getRecordTimeLength());
                        } else {
                            showLoadingDialog("下载中，请稍后...");
                            DownloadHelper
                                    .download(ApiConstants.getUploadFileUrl(dataContentBeans.get(position).getFileId()), SdCard.getAudio(),
                                            dataContentBeans.get(position).getFileId() + ".mp3", new DownloadHelper.OnDownloadListener() {
                                                @Override
                                                public void onDownloadSuccess(final String path) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            dismissLoadingDialog();
                                                            initDialogAndStartPlay(path, dataContentBeans.get(position).getRecordTimeLength());
                                                        }
                                                    });

                                                }

                                                @Override
                                                public void onDownloading(int progress) {
                                                }

                                                @Override
                                                public void onDownloadFailed() {
                                                    dismissLoadingDialog();
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            showShortToast("下载失败");
                                                        }
                                                    });
                                                }
                                            });
                        }
                    }
                });
            }
            return view;
        }
    }
}

